package com.sky.interceptor;

import com.sky.constant.JwtClaimConstant;
import com.sky.context.BaseContext;
import com.sky.exceptionHandler.JwtException;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class JwtUserInterceptor implements HandlerInterceptor {


    private JwtProperties jwtProperties;

    public JwtUserInterceptor(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入用户拦截器...");

        // 1. 如果不是 controller 直接放行
        if (!(handler instanceof HandlerMethod)) return true;

        String token = request.getHeader(jwtProperties.getUserTokenName());

        try {
            Claims claims = JwtUtils.parseJWT(jwtProperties.getUserSecretKey(), token);
            String userId = claims.get(JwtClaimConstant.USER_ID).toString();
            Long id = Long.valueOf(userId);
            BaseContext.setCurrentId(id);
        } catch (Exception e) {
            String requestURI = request.getRequestURI();
            throw new JwtException(504, String.format("没有「%s」的权限", requestURI));
        }

        // 调用接口的默认实现
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
